package app.framework.security.util;

import app.framework.constant.FrameworkCacheConstants;
import cn.hutool.core.util.ObjectUtil;
import jasmine.framework.cache.CacheUtil;

/**
 * <p>
 * 记录和查询登录的重试次数。
 * </p>
 *
 * @author mh.z
 */
public class LoginAttemptCountUtil {

    /**
     * 累加尝试次数
     *
     * @param username
     */
    public static void incrementAttemptCount(String username) {
        String cacheKey = ObjectUtil.defaultIfNull(username, "");

        // 暂时认为没有必要严格保证该逻辑的原子操作
        int attemptCount = getAttemptCount(cacheKey);
        attemptCount = attemptCount + 1;

        CacheUtil.set(FrameworkCacheConstants.CACHE_CATEGORY_LOGIN_ATTEMPT_COUNT,
                cacheKey, attemptCount, FrameworkCacheConstants.CACHE_TIMEOUT_LOGIN_ATTEMPT_COUNT);
    }

    /**
     * 返回尝试次数
     *
     * @param username
     * @return
     */
    public static int getAttemptCount(String username) {
        String cacheKey = ObjectUtil.defaultIfNull(username, "");
        Integer attemptCount = CacheUtil.get(FrameworkCacheConstants.CACHE_CATEGORY_LOGIN_ATTEMPT_COUNT,
                cacheKey, Integer.class);

        if (attemptCount == null) {
            return 0;
        }

        return attemptCount;
    }

    /**
     * 重置尝试次数
     *
     * @param username
     */
    public static void resetAttemptCount(String username) {
        String cacheKey = ObjectUtil.defaultIfNull(username, "");

        CacheUtil.remove(FrameworkCacheConstants.CACHE_CATEGORY_LOGIN_ATTEMPT_COUNT, cacheKey);
    }

}
